//
//  messageTableviewCell.m
//  SoundPill
//
//  Created by 宋旭东 on 16/3/7.
//  Copyright © 2016年 宋旭东. All rights reserved.
//

#import "messageTableviewCell.h"
#import "UIViewExt.h"
#import "UIImageView+WebCache.h"
#import "AFNetworking.h"
#import "EaseConvertToCommonEmoticonsHelper.h"
#import "EMTextMessageBody.h"
#import "WZLBadgeImport.h"
#define kleftGap  10
#define kupGap   12
#define kDeviceWidth [UIScreen mainScreen].bounds.size.width
#define kImageViewWidth 40
#define kImageViewHeight 40
#define kLabelWidth [UIScreen mainScreen].bounds.size.width*0.35
#define kLabelHeight 60

@interface messageTableviewCell ()
@property (strong, nonatomic)    UIImageView *lineImage;

@end

@implementation messageTableviewCell

-(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self=[super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        [self initSubViews];
        self.backgroundColor=[UIColor clearColor];
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        
    }
    return self;
}

- (void)initSubViews
{
    self.avatar = [[UIImageView alloc] initWithFrame:CGRectZero];
    [self addSubview:_avatar];
    
    self.username = [[UILabel alloc] initWithFrame:CGRectZero];
    [self addSubview:_username];
    
    self.date = [[UILabel alloc] initWithFrame:CGRectZero];
    [self addSubview:_date];
    
    // 描述
    self.detaillable = [[UILabel alloc] initWithFrame:CGRectZero];
    _detaillable.backgroundColor = [UIColor whiteColor];
    [self addSubview:_detaillable];
    
    self.lineImage = [[UIImageView alloc] initWithFrame:CGRectZero];
    [self addSubview:_lineImage];
}
- (void)layoutSubviews
{
    [super layoutSubviews];
    NSDictionary *chatDict = [[NSUserDefaults standardUserDefaults] valueForKey:[NSString stringWithFormat:@"chat%@",_conversation.conversationId]];
    if (chatDict.count == 0) {
//        NSLog(@"111111");
        [self requestChatUserInfo:_conversation.conversationId];
    }
    _avatar.frame = CGRectMake(kleftGap, kupGap, self.height - (2 * kupGap), self.height - (2 * kupGap));
    _avatar.backgroundColor=[UIColor whiteColor];
    [_avatar setImageWithURL:[NSURL URLWithString:[chatDict valueForKey:@"chatAvatar"]] placeholderImage:[UIImage imageNamed:@"default_head"]];
    
    _username.frame = CGRectMake(_avatar.right + 10, _avatar.top, self.frame.size.width - (_avatar.right + 20), _avatar.height / 2);
    _username.font = [UIFont fontWithName:@"Helvetica-Bold" size:15.0f];
    _username.textColor = [UIColor blackColor];
    _username.text = [chatDict valueForKey:@"chatUsername"];//_conversation.conversationId;//@"???????";
    
    _date.frame = CGRectMake(_avatar.right + 10, _username.top,  self.frame.size.width - (_avatar.right + 20), _avatar.height / 2);
    _date.font = [UIFont systemFontOfSize:13];
    _date.textAlignment = NSTextAlignmentRight;
    _date.textColor = [UIColor colorWithRed:0.717 green:0.719 blue:0.727 alpha:1.000];

    
    _detaillable.textColor = [UIColor grayColor];
    _detaillable.font = [UIFont systemFontOfSize:14];

//    _detaillable.text = @"[图片]";//[NSString stringWithFormat:@"向你的作品 %@", _model.title];
    _detaillable.frame = CGRectMake(_avatar.right + 10, _username.bottom + 5,(self.frame.size.width - (_avatar.right + 10)) / 2, 16);
    _lineImage.backgroundColor = [UIColor colorWithRed:0.895 green:0.898 blue:0.908 alpha:1.000];
    _lineImage.frame = CGRectMake(0, self.frame.size.height, self.width, 0.5);
//    [_conversation unreadMessagesCount];
    if ([_conversation unreadMessagesCount] > 0) {

        [_avatar showBadgeWithStyle:WBadgeStyleNumber value:[_conversation unreadMessagesCount] animationType:WBadgeAnimTypeNone];
    } else {
        [_avatar clearBadge];
    }
    EMMessage *lastMessage = [_conversation latestMessage];
    if (lastMessage) {
        double timeInterval = lastMessage.timestamp ;
        if(timeInterval > 140000000000) {
            timeInterval = timeInterval / 1000;
        }
        NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSDate *lastDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
        NSString *lastDateStr = [formatter stringFromDate:lastDate];
        NSCalendar *gregorian = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
        [gregorian setFirstWeekday:2];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSDate *fromDate;
        NSDate *toDate;
        [gregorian rangeOfUnit:NSDayCalendarUnit startDate:&fromDate interval:NULL forDate:lastDate];
        [gregorian rangeOfUnit:NSDayCalendarUnit startDate:&toDate interval:NULL forDate:[NSDate date]];
        NSDateComponents *dayComponents = [gregorian components:NSDayCalendarUnit fromDate:fromDate toDate:toDate options:0];
        if (dayComponents.day == 0) {
            //        显示今天
            _date.text = [lastDateStr substringFromIndex:11];
        } else if (dayComponents.day == 1) {
            //        显示昨天
            _date.text = @"昨天";
        } else if (dayComponents.day < 7) {
            //        显示星期
            NSArray *weekdays = [NSArray arrayWithObjects: [NSNull null], @"星期日", @"星期一", @"星期二", @"星期三", @"星期四", @"星期五", @"星期六", nil];
            NSCalendarUnit calendarUnit = NSWeekdayCalendarUnit;
            NSDateComponents *theComponents = [gregorian components:calendarUnit fromDate:lastDate];
            _date.text = weekdays[theComponents.weekday];
        } else{
            _date.text = [lastDateStr substringToIndex:10];
        }
       
        EMMessageBody *messageBody = lastMessage.body;
        switch (messageBody.type) {
            case EMMessageBodyTypeImage:{
                _detaillable.text = @"[图片]";//NSEaseLocalizedString(@"message.image1", @"[image]");
            } break;
            case EMMessageBodyTypeText:{
                NSString *didReceiveText = [EaseConvertToCommonEmoticonsHelper
                                            convertToSystemEmoticons:((EMTextMessageBody *)messageBody).text];
                _detaillable.text = didReceiveText;
            } break;
            default:{
                
            } break;
        }
    }
}

- (void)requestChatUserInfo:(NSString *)uid
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];

    NSString *str =[NSString stringWithFormat:@"http://123.57.1.143/api/user/%@/show",uid];
    NSString *header = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
    [manager.requestSerializer setValue:header forHTTPHeaderField:@"authorization"];
    [manager GET:str parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString *avatarStr = [[responseObject objectForKey:@"data"] valueForKey:@"avatar"];
        [_avatar setImageWithURL:[NSURL URLWithString:avatarStr] placeholderImage:[UIImage imageNamed:@"default_head"]];
        NSString *usernameStr = [[responseObject objectForKey:@"data"] valueForKey:@"username"];
        _username.text = usernameStr;
        NSDictionary *chatUserInfo = [NSDictionary dictionaryWithObjectsAndKeys:avatarStr,@"chatAvatar",usernameStr,@"chatUsername", nil];
        [[NSUserDefaults standardUserDefaults] setObject:chatUserInfo forKey:[NSString stringWithFormat:@"chat%@",_conversation.conversationId]];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
- (void)awakeFromNib {
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
